﻿// <copyright file="NavigationServiceExtensions.cs" company="Ucaya">
// </copyright>
// <author>Ucaya</author>

namespace Channel9Kinect
{
    #region

    using System;
    using System.Windows.Navigation;

    using Channel9Kinect.Navigation;

    #endregion

    public static class NavigationServiceExtensions
    {
        #region Public Methods

        public static void NavigateTo<T>(this NavigationService navigationService, Uri source, T parameter)
        {
            LoadCompletedEventHandler loadCompleteHandler = null;
            NavigationFailedEventHandler failedHandler = null;
            loadCompleteHandler = (sender, e) =>
                {
                    navigationService.NavigationFailed -= failedHandler;
                    navigationService.LoadCompleted -= loadCompleteHandler;
                    var pageParameter = e.Content as IPageParameter<T>;
                    if (pageParameter != null)
                    {
                        pageParameter.LoadParameter(parameter);
                    }
                };

            failedHandler = (sender, e) =>
                {
                    navigationService.NavigationFailed -= failedHandler;
                    navigationService.LoadCompleted -= loadCompleteHandler;
                };

            navigationService.LoadCompleted += loadCompleteHandler;
            navigationService.NavigationFailed += failedHandler;
            navigationService.Navigate(source);
        }

        #endregion
    }
}